package com.vegetable.modules.entity.stock;

import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.springframework.format.annotation.DateTimeFormat;

import java.math.BigDecimal;
import java.util.Date;

/**
 * <p>
 * 成本单价变化源头记录
 * </p>
 *
 * @author wangruijie
 * @since 2024-03-21
 */
@Data
@TableName("cost_weight_change_source")
@ApiModel(value="成本单价变化源头记录", description="记录CostWeight字段变化的源头信息")
public class CostWeightChangeSource {
    
    @ApiModelProperty(value = "主键ID")
    private Long id;
    
    @ApiModelProperty(value = "追踪事务ID，用于标识同一条链路上的所有修改")
    private String ttid;
    
    @ApiModelProperty(value = "库存ID")
    @JsonSerialize(using = ToStringSerializer.class)
    private Long stockId;
    
    @ApiModelProperty(value = "商品ID")
    @JsonSerialize(using = ToStringSerializer.class)
    private Long commodityId;
    
    @ApiModelProperty(value = "商品名称")
    private String commodityName;
    
    @ApiModelProperty(value = "规格ID")
    @JsonSerialize(using = ToStringSerializer.class)
    private Long specsId;
    
    @ApiModelProperty(value = "规格名称")
    private String specsName;
    
    @ApiModelProperty(value = "库存批次编码")
    private String stockBatchNo;
    
    @ApiModelProperty(value = "变化前成本单价")
    private BigDecimal beforeCostWeight;
    
    @ApiModelProperty(value = "变化后成本单价")
    private BigDecimal afterCostWeight;
    
    @ApiModelProperty(value = "变化差值")
    private BigDecimal changeAmount;
    
    @ApiModelProperty(value = "变化前蔬菜单价")
    private BigDecimal beforeGoodsUnitPrice;
    
    @ApiModelProperty(value = "变化后蔬菜单价")
    private BigDecimal afterGoodsUnitPrice;
    
    @ApiModelProperty(value = "蔬菜单价变化差值")
    private BigDecimal goodsUnitPriceChangeAmount;
    
    @ApiModelProperty(value = "变化前包装单价")
    private BigDecimal beforePackageUnitPrice;
    
    @ApiModelProperty(value = "变化后包装单价")
    private BigDecimal afterPackageUnitPrice;
    
    @ApiModelProperty(value = "包装单价变化差值")
    private BigDecimal packageUnitPriceChangeAmount;
    
    @ApiModelProperty(value = "变化源头类型：1-订单价格修改，2-入库调整，3-费用分摊，4-重新包装，5-订单费用统计，6-订单费用影响检查")
    private Integer sourceType;
    
    @ApiModelProperty(value = "源头订单ID")
    @JsonSerialize(using = ToStringSerializer.class)
    private Long sourceOrderId;
    
    @ApiModelProperty(value = "源头订单编号")
    private String sourceOrderNo;
    
    @ApiModelProperty(value = "源头订单类型：1-代办交货，2-采购收货等")
    private Integer sourceOrderType;
    
    @ApiModelProperty(value = "关联商品ID（如打包原料的商品ID）")
    @JsonSerialize(using = ToStringSerializer.class)
    private Long relatedCommodityId;
    
    @ApiModelProperty(value = "关联商品名称")
    private String relatedCommodityName;
    
    @ApiModelProperty(value = "操作人ID")
    @JsonSerialize(using = ToStringSerializer.class)
    private Long operatorId;
    
    @ApiModelProperty(value = "操作人姓名")
    private String operatorName;
    
    @ApiModelProperty(value = "操作时间")
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    @JsonFormat(locale = "zh", timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
    private Date operateTime;
    
    @ApiModelProperty(value = "备注说明")
    private String remark;
    
    @ApiModelProperty(value = "详细信息")
    private String detailInfo;
    
    @ApiModelProperty(value = "订单费用变化信息（JSON格式）")
    private String orderCostChanges;
    
    /**
     * 获取订单费用名称
     * @return 订单费用名称
     */
    public String getOrderCostName() {
        if (this.orderCostChanges != null && !this.orderCostChanges.isEmpty()) {
            try {
                com.alibaba.fastjson.JSONObject orderCostJson = com.alibaba.fastjson.JSON.parseObject(this.orderCostChanges);
                if (orderCostJson != null) {
                    return orderCostJson.getString("costName");
                }
            } catch (Exception e) {
                // JSON解析失败
            }
        }
        return null;
    }
    
    /**
     * 获取订单费用变化前金额
     * @return 订单费用变化前金额
     */
    public java.math.BigDecimal getOrderCostBeforeAmount() {
        if (this.orderCostChanges != null && !this.orderCostChanges.isEmpty()) {
            try {
                com.alibaba.fastjson.JSONObject orderCostJson = com.alibaba.fastjson.JSON.parseObject(this.orderCostChanges);
                if (orderCostJson != null) {
                    return orderCostJson.getBigDecimal("beforeCost");
                }
            } catch (Exception e) {
                // JSON解析失败
            }
        }
        return null;
    }
    
    /**
     * 获取订单费用变化后金额
     * @return 订单费用变化后金额
     */
    public java.math.BigDecimal getOrderCostAfterAmount() {
        if (this.orderCostChanges != null && !this.orderCostChanges.isEmpty()) {
            try {
                com.alibaba.fastjson.JSONObject orderCostJson = com.alibaba.fastjson.JSON.parseObject(this.orderCostChanges);
                if (orderCostJson != null) {
                    return orderCostJson.getBigDecimal("afterCost");
                }
            } catch (Exception e) {
                // JSON解析失败
            }
        }
        return null;
    }
    
    /**
     * 获取订单费用变化差额
     * @return 订单费用变化差额
     */
    public java.math.BigDecimal getOrderCostChangeAmount() {
        if (this.orderCostChanges != null && !this.orderCostChanges.isEmpty()) {
            try {
                com.alibaba.fastjson.JSONObject orderCostJson = com.alibaba.fastjson.JSON.parseObject(this.orderCostChanges);
                if (orderCostJson != null) {
                    return orderCostJson.getBigDecimal("costChange");
                }
            } catch (Exception e) {
                // JSON解析失败
            }
        }
        return null;
    }
    
    // 添加这个注解来确保getSourceTypeDescription方法被序列化
    @ApiModelProperty(value = "变化类型描述")
    public String getSourceTypeDescription() {
        switch (this.sourceType) {
            case 1: return "订单价格修改";
            case 2: return "入库调整";
            case 3: return "费用分摊";
            case 4: return "重新包装";
            case 5: return "订单费用统计";
            case 6: return "订单费用影响检查";
            default: return "其他";
        }
    }
    
    /**
     * 获取源头订单类型描述
     * @return 订单类型描述
     */
    public String getSourceOrderTypeDescription() {
        if (this.sourceOrderType != null) {
            switch (this.sourceOrderType) {
                case 1: return "代办交货";
                case 2: return "采购收货";
                default: return "其他订单";
            }
        }
        return "未知订单类型";
    }
    
    /**
     * 获取变化方向描述
     * @return 变化方向描述
     */
    public String getChangeDirection() {
        if (this.changeAmount != null) {
            if (this.changeAmount.compareTo(BigDecimal.ZERO) > 0) {
                return "成本增加";
            } else if (this.changeAmount.compareTo(BigDecimal.ZERO) < 0) {
                return "成本减少";
            } else {
                return "成本无变化";
            }
        }
        return "未知";
    }
    
    /**
     * 获取变化幅度描述
     * @return 变化幅度描述
     */
    public String getChangeMagnitude() {
        if (this.beforeCostWeight != null && this.beforeCostWeight.compareTo(BigDecimal.ZERO) != 0) {
            BigDecimal percentage = this.changeAmount.multiply(new BigDecimal("100"))
                .divide(this.beforeCostWeight, 2, BigDecimal.ROUND_HALF_UP);
            return percentage.toString() + "%";
        }
        return "0%";
    }
    
    /**
     * 获取详细的变化信息
     * @return 详细变化信息
     */
    public String getDetailedChangeInfo() {
        StringBuilder info = new StringBuilder();
        info.append("商品: ").append(this.commodityName != null ? this.commodityName : "未知");
        info.append(", 变化前成本: ").append(this.beforeCostWeight != null ? this.beforeCostWeight : "未知");
        info.append(", 变化后成本: ").append(this.afterCostWeight != null ? this.afterCostWeight : "未知");
        info.append(", 变化幅度: ").append(this.getChangeMagnitude());
        info.append(", 变化方向: ").append(this.getChangeDirection());
        
        if (this.sourceOrderNo != null) {
            info.append(", 源订单: ").append(this.sourceOrderNo);
        }
        
        if (this.remark != null) {
            info.append(", 备注: ").append(this.remark);
        }
        
        return info.toString();
    }
    
    /**
     * 判断是否为订单费用相关的变化
     * @return 是否为订单费用相关的变化
     */
    public boolean isOrderCostRelated() {
        return this.sourceType != null && (this.sourceType == 5 || this.sourceType == 6);
    }
    
    /**
     * 获取订单费用变化的详细描述
     * @return 订单费用变化的详细描述
     */
    public String getOrderCostChangeDescription() {
        if (!isOrderCostRelated()) {
            return "";
        }
        
        // 如果有订单费用变化的JSON信息，优先使用JSON信息
        if (this.orderCostChanges != null && !this.orderCostChanges.isEmpty()) {
            try {
                // 解析JSON格式的订单费用变化信息
                com.alibaba.fastjson.JSONObject orderCostJson = com.alibaba.fastjson.JSON.parseObject(this.orderCostChanges);
                if (orderCostJson != null) {
                    StringBuilder description = new StringBuilder();
                    
                    // 根据sourceType确定前缀
                    if (this.sourceType == 5) {
                        description.append("订单费用统计变化");
                    } else if (this.sourceType == 6) {
                        description.append("订单费用影响检查");
                    }
                    
                    // 添加费用名称
                    String costName = orderCostJson.getString("costName");
                    if (costName != null && !costName.isEmpty()) {
                        description.append(" - ").append(costName);
                    }
                    
                    // 添加费用差额信息
                    java.math.BigDecimal costChange = orderCostJson.getBigDecimal("costChange");
                    if (costChange != null) {
                        description.append(" (差额: ").append(costChange.stripTrailingZeros().toPlainString()).append(")");
                    }
                    
                    return description.toString();
                }
            } catch (Exception e) {
                // JSON解析失败，使用原有逻辑
                // 这里可以添加日志记录
            }
        }
        
        // 原有逻辑作为备选方案
        StringBuilder description = new StringBuilder();
        if (this.sourceType == 5) {
            description.append("订单费用统计变化");
        } else if (this.sourceType == 6) {
            description.append("订单费用影响检查");
        }
        
        if (this.commodityName != null && this.commodityName.contains(" - ")) {
            String[] parts = this.commodityName.split(" - ", 2);
            if (parts.length == 2) {
                description.append(" - ").append(parts[1]); // 费用类型名称
            }
        }
        
        return description.toString();
    }
}